package db;

import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;


public class DatabaseInfo
{
	private DataAccessObject dao;
	private DatabaseMetaData metaData;
	
	/**
	 * DatabaseInfo encapsulates information about a database<br>
	 * Including:<br>
	 * * Info about tables<br>
	 * * Info about table columns<br>
	 * * Etc...<br>
	 * Usually used inside of a DataAccessObject to extend functionality
	 * @param dao - a DataAccessObject to access the db
	 */
	public DatabaseInfo(DataAccessObject dao)
	{
		this.dao = dao;
		
		try
		{
			this.metaData = dao.getDbConnection().getMetaData();
		}
		catch(SQLException e) { e.printStackTrace(); }
	}
	
	//-------------------------------------
	//---------Database Meta Data--------//
	//-------------------------------------
	/**
	 * Get the meta data object full of interesting information
	 * about the database
	 * @return DatabaseMetaData - meta data object for database
	 */
	public DatabaseMetaData getMetaData()
	{
		return metaData;
	}
	
	/**
	 * Get the names of the columns in a table
	 * @param tableName
	 * @return String[] with column names
	 */
	public String[] getTableColNames(String tableName)
	{
		String selectString = "SELECT * FROM " + tableName;
		ResultSet results = null;
		ResultSetMetaData rsmd = null;
		String[] cols = null;
		try
		{
			Statement selectStmt = dao.getDbConnection().createStatement();
			results = selectStmt.executeQuery(selectString);
			rsmd = results.getMetaData();
			cols = new String[rsmd.getColumnCount()];
			for(int i = 0; i < rsmd.getColumnCount(); i++)
			{
				cols[i] = rsmd.getColumnName(i+1);
			}
		}
		catch (SQLException e) { e.printStackTrace(); }
	
		return cols;
	}
	
}
